package cn.gzsxt.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import cn.gzsxt.po.Build;
import cn.gzsxt.po.Floor;
import cn.gzsxt.po.Room;
import cn.gzsxt.service.ConstractService;
import cn.gzsxt.service.impl.ConstractServiceImpl;

@WebServlet("/handlerConstract.gzsxt")
public class HandlerConstractControler extends HttpServlet {
	private static final long serialVersionUID = 1L;

	// 引入service层
	private ConstractService service = new ConstractServiceImpl();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("application/json;charset=utf-8");
		// 接受标识参数
		String cmd = req.getParameter("cmd");
		// 获取 楼栋 getBuild ,层 getFloor , 房间 getRoom
		if ("getFloor".equals(cmd)) {
			// 加载楼层
			getFloor(req, resp);
		} else if ("getRoom".equals(cmd)) {
			// 加载房间
			getRoom(req, resp);
		} else {
			getBuild(req, resp);
		}
	}

	// 根据楼层的id查询出对应的房间
	private void getRoom(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException{
		String id = req.getParameter("id");
		List<Room> rooms = service.getRoomByFloorId(Integer.valueOf(id));

		// 将list集合转换成json格式的字符串响应给前台
		resp.getWriter().print(JSON.toJSONString(rooms));
	}

	// 根据楼栋的id查询出对应的楼层
	private void getFloor(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String id = req.getParameter("id");
		List<Floor> floors = service.getFloorByBuildId(Integer.valueOf(id));
		// 将list集合转换成json格式的字符串响应给前台
		resp.getWriter().print(JSON.toJSONString(floors));
	}

	// 获取所有的楼栋
	private void getBuild(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// 调用业务层获取所有楼栋的方法
		List<Build> builds = service.getBuild();

		// 将list集合转换成json格式的字符串响应给前台
		resp.getWriter().print(JSON.toJSONString(builds));
	}

}
